package org.cocos2dx.javascript.Mob;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.mob.MobSDK;
import com.mob.secverify.PreVerifyCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.VerifyCallback;
import com.mob.secverify.common.exception.VerifyException;
import com.mob.secverify.datatype.LandUiSettings;

import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.javascript.Contants;
import org.cocos2dx.javascript.NativeMgr;
import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.wrapper.TokenVerifyResult;



public class PhoneLoginMgr {
    public static PhoneLoginMgr _instance = null;
    private Context _context;
    private MobCallBack logincallBack = null;
    private boolean isVerifySupport = false;
    private NormalLoginDialog normalDialog = null;
    private OtherPhoneDialog otherPhoneDialog = null;
    private String otherPhoneNum = "";
    public String appCompany = "zqhy";
    public String packageIdx = "1";

    public String PhoneVerifyIP = "http://47.92.192.155:";
    public String PhoneVerifyPort = "901";

    private String urlQuickSms = PhoneVerifyIP + PhoneVerifyPort +"?token=%s&opToken=%s&operator=%s&type=1&packageIdx=%s";
    private String urlSmsSdk = PhoneVerifyIP + PhoneVerifyPort +"?appkey=%s&phone=%s&code=%s&zone=86&type=2&packageIdx=%s";

    public static PhoneLoginMgr getInstance() {
        if (_instance == null) _instance = new PhoneLoginMgr();

        return _instance;
    }

    public void init(Context context){
        
        this._context = context;

        MobSDK.submitPolicyGrantResult(true, null);

        isVerifySupport = SecVerify.isVerifySupport();
        if (isVerifySupport) {
            this.initVerifyCodeHandler();

            SecVerify.setLandUiSettings(new LandUiSettings.Builder().build() );
            SecVerify.setAdapterClass(DialogAdapter.class );
         
            //SecVerify.setAdapterFullName("org.cocos2dx.javascript.Mob.DialogAdapter");
            SecVerify.autoFinishOAuthPage(false);
            preVerify();
        } else {
            Log.w("PhoneSdk", "当前环境不支持一键登录, error: SecVerify.isVerifySupport");
        }
    }

    public void otherPhoneLogin(){
        this.otherPhoneDialog = new OtherPhoneDialog(_context);
        this.otherPhoneDialog.show();
    }

    public void login(MobCallBack callBack) throws JSONException {
        this.logincallBack = callBack;
        ((AppActivity)_context).requestPermission();
    }

    public void loginSucc(String strJson) throws JSONException {
        this.logincallBack.onSuccess(strJson);
    }

    /**
     * 预登录
     * <p>
     * 建议提前调用预登录接口，可以加快免密登录过程，提高用户体验
     */
    private void preVerify() {
        //设置在1000-10000之内
        SecVerify.setTimeOut(5000);
        //移动的debug tag 是CMCC-SDK,电信是CT_ 联通是PriorityAsyncTask
        SecVerify.setDebugMode(true);
        SecVerify.preVerify(new PreVerifyCallback() {
            @Override
            public void onComplete(Void data) {
            }

            @Override
            public void onFailure(VerifyException e) {
                // Nothing to do
                Throwable t = e.getCause();
                String errDetail = null;
                if (t != null) {
                    errDetail = t.getMessage();
                }

                // 登录失败
                Log.e("PhoneSdk", "preVerify failed", e);
                // 错误码
                int errCode = e.getCode();
                // 错误信息
                String errMsg = e.getMessage();
                // 更详细的网络错误信息可以通过t查看，请注意：t有可能为null
                String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
                if (!TextUtils.isEmpty(errDetail)) {
                    msg += "\n详细信息: " + errDetail;
                }
                Log.e("PhoneSdk", msg);
            }
        });
    }

    private void initVerifyCodeHandler(){
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                // TODO 此处为子线程！不可直接处理UI线程！处理后续操作需传到主线程中操作！
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //成功回调
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交短信、语音验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取短信验证码成功
                        Log.e("PhoneSdk", "发送验证码成功");
                        //SMSSDK.submitVerificationCode("86", etPhone.getText().toString().trim(), etCode.getText().toString());
                    } else if (event == SMSSDK.EVENT_GET_VOICE_VERIFICATION_CODE) {
                        //获取语音验证码成功
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }else if (event == SMSSDK.EVENT_GET_VERIFY_TOKEN_CODE) {
                        //本机验证获取token成功
                        TokenVerifyResult tokenVerifyResult = (TokenVerifyResult) data;
                        //SMSSDK.login(phoneNum,tokenVerifyResult);
                    }else if (event == SMSSDK.EVENT_VERIFY_LOGIN) {
                        //本机验证登陆成功
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
                    //失败回调
                } else {
                    //其他失败回调
                    ((Throwable) data).printStackTrace();
                }
            }
        };
    }

    public void requestPermissionCallback(boolean bSuccess) throws JSONException {
        if (this.logincallBack == null) {
            Log.w("CallBack", "回调函数不存在,不执行回调");
            return;
        }

        if (bSuccess){
            String phoneNumber = SdkSetting.getSetting(_context, "phoneNumber");
            Log.i("requestPermissionCallback", "phoneNumber:" + phoneNumber );
            if (isVerifySupport && (phoneNumber == "")){
                Log.i("requestPermissionCallback", "0" );
                SecVerify.verify(new VerifyCallback() {
                    @Override
                    public void onOtherLogin() {
                        // 用户点击“其他登录方式”，处理自己的逻辑
                    }
                    @Override
                    public void onUserCanceled() {
                        // 用户点击“关闭按钮”或“物理返回键”取消登录，处理自己的逻辑
                    }

                    @Override
                    public void onComplete(com.mob.secverify.datatype.VerifyResult verifyResult) {
                        // 获取授权码成功，将token信息传给应用服务端，再由应用服务端进行登录验证，此功能需由开发者自行实现
                        //这里使用data.getOpToken()把获取到的token搭配服务端API进行验证
                        String opToken = verifyResult.getOpToken();   //运营商token
                        String token = verifyResult.getToken();   //服务器token
                        String operator = verifyResult.getOperator();   //运营商类型，[CMCC:中国移动，CUCC：中国联通，CTCC：中国电信]
                        Log.i("phoneSdk", "获得授权码成功 " + opToken + "-" + token + "-" + operator);

                        Context context = _context;
                        Handler handler = ((AppActivity)_context).getPhoneHandler();
                        Log.i("requestPermissionCallback", "urlQuickSms:" + String.format(urlQuickSms, token, opToken, operator, packageIdx) );
                       
                        NetworkUtil.httpPost(handler, String.format(urlQuickSms, token, opToken, operator, packageIdx), Contants.MSG_PHONE_VERIFY_LOGIN);
                    }

                    @Override
                    public void onFailure(com.mob.secverify.common.exception.VerifyException e) {
                        //如果是无sim卡的话
                        if (e.getCode() == 6119002){
                            Toast.makeText(AppActivity.getInstance(), "没有安装手机卡，请先安装手机卡", Toast.LENGTH_LONG).show();
                        }
                        Log.e("phoneSdk", e.toString());
                    }
                });
            }
            else{
                if (phoneNumber != ""){
                    logincallBack.onSuccess(phoneNumber);
                }
                else{
                    normalDialog = new NormalLoginDialog(_context);
                    normalDialog.show();
                }
            }
        }
        else{
            logincallBack.onFail("授权失败,无法登录");
        }
    }

    public void handleMessage(Handler handler, Message msg) {
        try {
            switch (msg.what) {
                case Contants.MSG_QUICK_GET_PHONE:
                    this.onQuickGetPhone((String) msg.obj);
                    break;
                case Contants.MSG_PHONE_VERIFY_LOGIN:
                    this.onVerifyLogin((String)msg.obj);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e){
            Log.e("handleMessage", "请求接口数据回包错误");
        }
    }

    public void onVerifyLogin(String strJson){
        try {
            JSONObject json = new JSONObject(strJson);
            int isValid = json.getInt("isValid");
            String phone = json.getString("phone");
            boolean valid = json.getBoolean("valid");

            JSONObject mJsonobjData = new JSONObject();
            mJsonobjData.put("phone", phone);
            mJsonobjData.put("valid", valid);
            
            
            NativeMgr.OnCallBackToJs("OnPhoneLogin", mJsonobjData.toString());

            SecVerify.finishOAuthPage();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void onQuickGetPhone(String strJson){
        try {
         
            Log.i("onQuickGetPhone", "strJson:" + strJson);

            JSONObject json = new JSONObject(strJson);
            JSONObject mJsonobjData = new JSONObject();
            int status = json.getInt("status");
            if  (status == 200) {
                mJsonobjData.put("phone", otherPhoneNum);
                mJsonobjData.put("valid", true);
                NativeMgr.OnCallBackToJs("OnPhoneLogin", mJsonobjData.toString());
                SecVerify.finishOAuthPage();
            }
            else {
                Toast.makeText(AppActivity.getInstance(), "验证码填写错误，请检查清楚后再填写", Toast.LENGTH_LONG).show();
            }
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void specialLogin(String phoneNumber, String verifyCode){
        Context context = _context;
        otherPhoneNum = phoneNumber;
        Handler handler = ((AppActivity)_context).getPhoneHandler();
        NetworkUtil.httpPost(handler, String.format(urlSmsSdk, Contants.MOB_APP_KEY, phoneNumber, verifyCode, packageIdx), Contants.MSG_QUICK_GET_PHONE);
    }


    public void setAppInfo(String company, String idx){

         
        Log.e("setAppInfo", "appCompany:" + company + " idx: "+ idx);
        packageIdx = idx;
        appCompany = company;
        
    }

    public String getAppCompany(){
        return appCompany;
    }

}
